package com.johnny.xia.util.base;
import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;
import java.nio.charset.StandardCharsets;
import java.security.MessageDigest;
import java.util.Base64;

public class Aes128 {
    public static String encrypt(String plaintext, String encryptionKey, String initializationVector) throws Exception {
        SecretKeySpec keySpec = new SecretKeySpec(encryptMD5(encryptionKey.getBytes(StandardCharsets.UTF_8)), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(initializationVector.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.ENCRYPT_MODE, keySpec, ivSpec);
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes(StandardCharsets.UTF_8));
        return Base64.getEncoder().encodeToString(encryptedBytes);
    }

    public static String decrypt(String ciphertext, String encryptionKey, String initializationVector) throws Exception {
        byte[] encryptedBytes = Base64.getDecoder().decode(ciphertext);
        SecretKeySpec keySpec = new SecretKeySpec(encryptMD5(encryptionKey.getBytes(StandardCharsets.UTF_8)), "AES");
        IvParameterSpec ivSpec = new IvParameterSpec(initializationVector.getBytes(StandardCharsets.UTF_8));
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        cipher.init(Cipher.DECRYPT_MODE, keySpec, ivSpec);
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, StandardCharsets.UTF_8);
    }

    public static byte[] encryptMD5(byte[] data) throws Exception {
        MessageDigest md = MessageDigest.getInstance("MD5");
        return md.digest(data);
    }

    public static  void main(String[] args) throws Exception {
        String plaintext = "Data to be encrypted";
        String initializationVector = "XTpGtALYd6rUuIbP";
        String  appSecret =  "b5a2856444a54a84d9b20890180fdda6";

        // 加密
        String encryptedText = Aes128.encrypt(plaintext, appSecret, initializationVector);
        System.out.println("加密后的文本: " + encryptedText);

        // 解密
        String decryptedText = Aes128.decrypt(encryptedText, appSecret, initializationVector);
        System.out.println("解密后的文本: " + decryptedText);
    }
}
